<template>
	<view class="register-page">
		<!-- logo -->
		<view class="logo-box">
			<image class="logo-img" src="/static/logo.png" mode="aspectFit" />
		</view>

		<!-- 输入框 -->
		<form class="input-box" :model="registerForm" @submit="onSubmit" :rules="rules" >
			<view class="input-row">
				<image class="input-icon" src="/static/login_phone.png" mode="aspectFit" />
				<input class="input" v-model="registerForm.phone" type="text" placeholder="请输入手机号" />
			</view>
			<view class="input-row">
				<image class="input-icon" src="/static/login_phone.png" mode="aspectFit" />
				<input class="iv-nput" v-model="registerForm.code" type="text" placeholder="请输入短信验证码" />
				<text v-show="agree" class="sms-btn"  @click="getCode" >{{ buttonTxt }}</text>
			</view>
			<view class="input-row">
				<image class="input-icon" src="/static/login_password.png" mode="aspectFit" />
				<input class="input" type="password" v-model="registerForm.password" placeholder="请输入登录密码" />
			</view>
			<view class="input-row">
				<image class="input-icon" src="/static/login_password.png" mode="aspectFit" />
				<input class="input" type="confirmPassword" v-model="registerForm.confirmPassword" placeholder="请再次输入登录密码" />
			</view>
			<view class="input-row">
				<image class="input-icon" src="/static/login_password.png" mode="aspectFit" />
				<input class="input" type="text" v-model="registerForm.invitation_code" placeholder="邀请码" />
			</view>
			<!-- <view class="input-row">
				<image class="input-icon" src="/static/icon-pwd.png" mode="aspectFit" />
				<input class="input" type="text" placeholder="图片验证码" />
				<image class="captcha-img" src="/static/captcha.png" mode="aspectFit" />
			</view> -->
		</form>

		<!-- 注册按钮 -->
		<view class="register-btn-box">
			<button class="register-btn" @click="onSubmit">注册</button>
			<view class="forget">
				
				<navigator class="toLogin" url="/pages/login/login" >已有账号,登录</navigator >
				<navigator class="toForget forgetFont"  url="/pages/user/forget/forget">忘记密码</navigator>
			</view>
			
		</view>

		<!-- 协议 -->
		<view class="protocol-row">
			<image class="checked-icon" src="/static/check_box_checked.png" mode="aspectFit" />
			<text class="protocol-text">
				注册即代表您同意
				<text>《米多鱼s<text class="protocol-link" @click="navigatorInst(agreementintro.id)">{{ agreementintro.title }}</text>和<text class="protocol-link" @click="navigatorInst(privacyintro.id)">{{ privacyintro.title }}</text>》</text>
			</text>
		</view>

		<!-- 协议弹窗 -->
		<view v-if="showProtocol" class="modal-mask">
			<view class="modal-box">
				<view class="modal-title">{{reminderintro.title}}</view>
				
				<view class="modal-content">
					<rich-text :nodes="reminderintro.content"></rich-text>
				</view>
				<view class="modal-btn-row">
					<view class="modal-btn reject" @click="onReject">拒绝</view>
					<view class="modal-btn agree" @click="onAgree">同意</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
import { ref,reactive } from 'vue'
import { getPhoneCode, register } from "@/api/member.js"
import { onLoad } from '@dcloudio/uni-app';
import { getSysIntroByMark } from "@/api/sysIntro.js"
const loading = ref(false);
const buttonTxt = ref("获取验证码");
const codeDisabled = ref(false);

const reminderintro = reactive({
	title:"",
	description:"",
	content:""
})
const privacyintro = reactive({
	title:"",
	id:0
})
const agreementintro = reactive({
	title:"",
	id:0
})
const agree = ref(false);
onLoad((options) => {
	
	console.log("onLoad");
	
	if((uni.getStorageSync("token") || '')){
		uni.switchTab({
			url: '/pages/index/index'
		});
	}
	
	getSysIntro();
});
const getSysIntro = async()=>{
		await getSysIntroByMark({"mark":"privacy,reminder,agreement"}).then(result=>{
			console.log(result);
			Object.assign(reminderintro, result.find(item => item.mark === 'reminder'));
			Object.assign(agreementintro, result.find(item => item.mark === 'agreement'));
			Object.assign(privacyintro, result.find(item => item.mark === 'privacy'));
			showProtocol.value=true;
			console.log(privacyintro);
		})
	}
const registerForm = ref({
  phone: '',
  code: '',
  password:'',
  confirmPassword:'',
  invitation_code:'',
  pid:uni.getStorageSync("mid") || 0
});
const showProtocol = ref(false)
function onReject() {
	showProtocol.value = false
	// 可加提示或跳转
	agree.value=false;
	uni.showToast({
	      title: '您拒绝了用户协议和隐私权政策不能注册平台账户',
	      icon: 'none'
	})
}
function onAgree() {
	showProtocol.value = false
	// 可加同意后逻辑
	agree.value=true;
}
const getCode = async ()=>{
	if(codeDisabled.value) return;
	let phone=registerForm.value?.phone;
	if(!phone) {
		uni.showModal({
			title: '提示',
			content: '请输入手机号'
		});
		return false;
	}
	buttonTxt.value = 60;
		
	codeDisabled.value=true;
		
	let countdown = setInterval(() => {
				if (buttonTxt.value > 1) {
					buttonTxt.value -= 1;
				} else {
					clearInterval(countdown);
					buttonTxt.value = "重新获取验证码";
					codeDisabled.value = false;
				}
	}, 1000);
	try {
		
		let res = await getPhoneCode({phone:phone});
	} catch (err) {
		clearInterval(countdown);
		buttonTxt.value = "重新获取验证码";
		codeDisabled.value = false;
		console.error('请求失败：', err);
	}finally{
		loading.value = false;
	}
}
//提交表单
const onSubmit =  async ()=>{
	
	let isValid = await validateForm();
	    // 如果表单数据不合法，则终止操作
	if (!isValid) return;
	
	loading.value = true;
	try {
		let res = await register(registerForm.value);
		if (res) {
			console.log('Registration successful:', res);
			uni.showModal({
				title: '提示',
				content: '注册成功',
				showCancel: false,
				success: () => {
					uni.navigateTo({
						url: '/pages/login/login'
					});
				}
			});
		} else {
			console.error('Registration failed:', res?.message || 'Unknown error');
		}
	} catch (err) {
		console.error('请求失败：', err);
	}finally{
		loading.value = false;
	}
}
// 验证规则
const rules = {
	phone: [
	  { required: true, message: '请输入手机号', trigger: 'change' },
	  { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号', trigger: 'change' }
	],
	code: [
	  { required: true, message: '请输入短信验证码', trigger: 'change' }
	],
	password: [
	  { required: true, message: '请输入密码', trigger: 'change' }
	],
	confirmPassword: [
	  { required: true, message: '请输入确认密码', trigger: 'change' }
	]
  };
  

const validateForm = async () => {
		const messages = Object.keys(rules).reduce((acc, key) => {
			const fieldRules = rules[key];
			const value = registerForm.value[key];
			fieldRules.forEach(rule => {
				if (rule.required && !value) {
					acc.push(rule.message);
					return;
				} else if (rule.pattern && !rule.pattern.test(value)) {
					acc.push(rule.message);
					return;
				}
			});
			return acc;
		}, []);

		if (messages.length > 0) {
			uni.showModal({
				title: '提示',
				content: messages.join('\n'),
				icon: "none"
			});
			return false;
		}
		return true;
};
const navigatorInst = (id)=>{
	uni.navigateTo({
		url:`/pages/index/instructions/instructions?id=${id}`
	});
}
</script>

<style scoped>
.register-page {
	min-height: 100vh;
	background: #fff;
	display: flex;
	flex-direction: column;
	align-items: center;
	padding-bottom: 40rpx;
}
.logo-box {
	margin-top: 80rpx;
	margin-bottom: 60rpx;
	width: 100%;
	display: flex;
	justify-content: center;
}
.logo-img {
	width: 160rpx;
	height: 160rpx;
	border-radius: 16rpx;
	background: #4a90e2;
}
.input-box {
	width: 80vw;
	max-width: 600rpx;
	margin-bottom: 48rpx;
}
.input-row {
	display: flex;
	align-items: center;
	background: #f2f2f2;
	border-radius: 60rpx;
	height: 80rpx;
	margin-bottom: 24rpx;
	padding: 0 32rpx;
	position: relative;
}
.input-icon {
	width: 26rpx;
	height: 26rpx;
	margin-right: 16rpx;
}
.input {
	flex: 1;
	border: none;
	background: transparent;
	font-size: 28rpx;
	color: #333;
	outline: none;
}
.sms-btn {
  color: #ff2d2d;
  font-size: 30rpx !important;
  margin-left: 18rpx;
  font-weight: bold;
  white-space: nowrap; /* 防止换行 */
  max-width: 100%; /* 确保不会超出父容器 */
}
.captcha-img {
	width: 100rpx;
	height: 48rpx;
	margin-left: 18rpx;
	border-radius: 8rpx;
	background: #fff;
	border: 2rpx solid #e0e0e0;
}
.register-btn-box {
	width: 80vw;
	max-width: 600rpx;
	margin-bottom: 40rpx;
	margin-top: 10rpx;
}
.register-btn {
	width: 100%;
	height: 90rpx;
	background: #4a90e2;
	color: #fff;
	font-size: 32rpx;
	border-radius: 60rpx;
	border: none;
	font-weight: bold;
	box-shadow: 0 4rpx 16rpx rgba(74,144,226,0.10);
}
.protocol-row {
	display: flex;
	align-items: center;
	justify-content: center;
	margin-bottom: 40rpx;
	margin-top: 20rpx;
}
.checked-icon {
	width: 32rpx;
	height: 32rpx;
	margin-right: 10rpx;
}
.protocol-text {
	font-size: 22rpx;
	color: #888;
}
.protocol-link {
	color: #4a90e2;
}
.modal-mask {
	position: fixed;
	left: 0; top: 0; right: 0; bottom: 0;
	background: rgba(0,0,0,0.35);
	z-index: 999;
	display: flex;
	align-items: center;
	justify-content: center;
}
.modal-box {
	width: 80vw;
	max-width: 600rpx;
	background: #fff;
	border-radius: 24rpx;
	padding: 40rpx 24rpx 24rpx 24rpx;
	box-shadow: 0 8rpx 32rpx rgba(0,0,0,0.10);
	display: flex;
	flex-direction: column;
	align-items: center;
}
.modal-title {
	font-size: 32rpx;
	font-weight: bold;
	color: #222;
	margin-bottom: 12rpx;
}
.modal-subtitle {
	font-size: 24rpx;
	color: #888;
	margin-bottom: 18rpx;
}
.modal-content {
	width: 100%;
	font-size: 24rpx;
	color: #333;
	margin-bottom: 32rpx;
}
.modal-content text {
	display: block;
	margin-bottom: 12rpx;
	line-height: 1.7;
}
.modal-btn-row {
	display: flex;
	width: 100%;
	justify-content: space-between;
	gap: 32rpx;
}
.modal-btn {
	flex: 1;
	text-align: center;
	padding: 18rpx 0;
	border-radius: 12rpx;
	font-size: 28rpx;
	font-weight: bold;
}
.modal-btn.reject {
	background: #f6f7fb;
	color: #4a90e2;
	border: 2rpx solid #4a90e2;
}
.modal-btn.agree {
	background: #4a90e2;
	color: #fff;
}
.forget{
	display:flex;
	margin: 25rpx 0;
}
.toLogin,.toForget{
	text-align: center;
	font-size: 30rpx;
	flex: 1;
}
.forgetFont{
	color: blue;
}
</style>
